﻿using System;

namespace AspNetMvc.Models
{
   public class PagedModel<T>
   {
      //ToDo: Add tests for this class

      public T Value { get; set; }

      public int ItemsCount { get; set; }
      public int Page { get; set; }
      public int ItemsPerPage { get; set; }

      private int _pagesCount = -1;
      public int PagesCount
      {
         get
         {
            if (_pagesCount == -1)
               _pagesCount = (int)Math.Ceiling((double)ItemsCount / ItemsPerPage);

            return _pagesCount;
         }
      }

      private int _pageStartItemIndex = -1;
      public int PageStartItemIndex
      {
         get
         {
            if (_pageStartItemIndex == -1)
               _pageStartItemIndex = (Page - 1) * ItemsPerPage + 1;

            return _pageStartItemIndex;
         }
      }

      private int _pageEndItemIndex = -1;
      public int PageEndItemIndex
      {
         get
         {
            if (_pageEndItemIndex == -1)
            {
               //theoretical maximum index for specified page
               int pageMaxEndItemIndex = Page * ItemsPerPage;

               //
               _pageEndItemIndex = pageMaxEndItemIndex < ItemsCount ? pageMaxEndItemIndex : ItemsCount;
            }
            return _pageEndItemIndex;
         }
      }

      public PagedModel(T value, int itemsCount, int page, int itemsPerPage)
      {
         Value = value;
         ItemsCount = itemsCount;
         Page = page;
         ItemsPerPage = itemsPerPage;
      }
   }
}